package org.yufan.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;
import org.yufan.bean.User;
import org.yufan.exception.CustomException;
import org.yufan.result.Result;
import org.yufan.result.ResultUtils;
import org.yufan.service.UserService;
import org.yufan.service.impl.UserServiceImpl;
import org.yufan.utils.JsonUtils;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by zxd on 2018/3/29.
 */
@RequestMapping("/user")
@Controller
public class UserController {

    private Logger LOGGER= LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/register")
    @ResponseBody
    public Result register(@Valid  User user, BindingResult bindingResult) throws CustomException {
        //判断是否有错误信息
        if(bindingResult.hasErrors()){
            //如果有返回错误信息
            String message = getString(bindingResult);
            return ResultUtils.buildFail(100,message);
        }

        LOGGER.info("注册用户，注册的用户信息是:{}",
                JsonUtils.objectToJson(user));
        userService.register(user);
        return ResultUtils.buildSuccess();
    }

       private String getString(BindingResult bindingResult) {
        List<ObjectError> errors = bindingResult.getAllErrors();
        List<String> list=new ArrayList<>();
        for (ObjectError error:errors) {
            String message = error.getDefaultMessage();
            LOGGER.info("错误信息是{}",message);
            //把错误信息存放到集合中
            list.add(message);
        }

        return org.apache.commons.lang3.StringUtils.join(list,",");
    }

    @RequestMapping(value = "/login")
    public ResponseEntity<Result> login(String username,String password) throws CustomException {
        if(StringUtils.isEmpty(username)){
            LOGGER.info("用户名为空!");
            return ResponseEntity.ok(ResultUtils.buildFail(101,"用户名为空!"));
        }
        if(StringUtils.isEmpty(password)){
            LOGGER.info("密码不能为空!");
            return ResponseEntity.ok(ResultUtils.buildFail(102,",密码为空!"));
        }
        LOGGER.info("当前登录的用户为{}",username);
        String token=userService.login(username,password);
        return ResponseEntity.ok(ResultUtils.buildSuccess(token));
    }

    @RequestMapping(value ="/{token}")
    public ResponseEntity<Result> queryUserByToken(@PathVariable("token")String token) throws CustomException {
        LOGGER.info("当前查询用户信息的token为{}",token);
        User user=userService.queryUserByToken(token);
        return ResponseEntity.ok(ResultUtils.buildSuccess(user));
    }


    @RequestMapping(value = "/loginByPhone")
    public ResponseEntity<Result> loginByPhone(String phone,String sms_code) throws CustomException {
        if(StringUtils.isEmpty(phone)){
            LOGGER.info("电话号码为空!");
            return ResponseEntity.ok(ResultUtils.buildFail(101,"用户名为空!"));
        }
        if(StringUtils.isEmpty(sms_code)){
            LOGGER.info("验证码不能为空!");
            return ResponseEntity.ok(ResultUtils.buildFail(102,",密码为空!"));
        }
        LOGGER.info("当前登录的手机为{}",phone);
        String token=userService.loginByPhone(phone,sms_code);
        return ResponseEntity.ok(ResultUtils.buildSuccess(token));
    }

    //短信注册   发送短信  发送验证码  校验是否注册过  存在服务器

    //短信注册  手机号码  验证码   生成用户名  修改


    /**
     * 1 username
     * 2 phone
     * 3 email
     * @return
     */
    /*
    @RequestMapping("/check/{param}/{type}")
    @ResponseBody
    public String check(@PathVariable("param")String param,
                        @PathVariable("type")Integer type, @RequestParam("callback")
                        String callback) throws CustomException {
        LOGGER.info("校验的类型是{},参数是{}",type,param);
        Boolean b=userService.check(param,type);
        Result result = ResultUtils.buildSuccess(b);

        String json=JsonUtils.objectToJson(result);

        if(StringUtils.isEmpty(callback)){
            return json;
        }else{
            return callback+"(" +json+");";
        }
    }
    */


    @RequestMapping("/check/{param}/{type}")
    @ResponseBody
    public Result check(@PathVariable("param")String param,
                        @PathVariable("type")Integer type) throws CustomException {
        LOGGER.info("校验的类型是{},参数是{}",type,param);
        Boolean b=userService.check(param,type);
        Result result = ResultUtils.buildSuccess(b);
        return result;
    }

}
